import type { Request, Response } from 'express';

import { z } from 'zod';

import { AppModel } from '../../../models/app';
import Resp from '../../../utils/response';

// 参数校验规则
export const validator = z.object({
  name: z.string().optional(),
  page: z
    .string()
    .regex(/^\d+$/, '页码必须是数字')
    .transform(Number)
    .refine(val => val > 0, '页码必须大于0')
    .optional(),
  pageSize: z
    .string()
    .regex(/^\d+$/, '每页数量必须是数字')
    .transform(Number)
    .refine(val => val > 0 && val <= 100, '每页数量必须在1-100之间')
    .optional(),
});

// 获取应用列表 API
export const api = async (req: Request, res: Response): Promise<Response> => {
  try {
    const { name, page, pageSize } = req.query as any as z.infer<typeof validator>;

    // 构建查询条件
    const query: Record<string, unknown> = {};
    if (name) query.name = { $options: 'i', $regex: name };

    // 执行查询
    let findQuery = AppModel.find(query).sort({ createdAt: -1 });

    // 如果提供了分页参数，则应用分页
    if (page && pageSize) {
      findQuery = findQuery.skip((Number(page) - 1) * Number(pageSize)).limit(Number(pageSize));
    }

    const [total, list] = await Promise.all([AppModel.countDocuments(query), findQuery]);

    // 返回成功响应
    // 构建响应数据
    const responseData = {
      list,
      total,
      ...(page && pageSize ? { page: Number(page), pageSize: Number(pageSize) } : {}),
    };

    return Resp.success(res, responseData, '获取应用列表成功');
  } catch (error) {
    console.error(error);
    return Resp.catch(res, error);
  }
};
